package com.hmall.order.mq;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.common.pojo.Item;
import com.hmall.feignclient.ItemFeignClient;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 苏成博
 * @date 2023-03-20 14:09
 */
@Component
public class OrderMqConsumer {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ItemFeignClient itemFeignClient;
    @RabbitListener(queues = "order.dead.queue")
    @GlobalTransactional
    public void handleOrderMessage(Long id){
        Order order = orderMapper.selectById(id);
        if (order.getStatus()!=1){
            //为2代表已付款未发货，若是十五分钟收到消息后已付款，则丢弃消息
            return;
        }
        if (order.getStatus()==1){
            //为1代表还未付款，若还未付款，则取消订单同时删除物流信息，恢复库存
            LambdaQueryWrapper<OrderDetail> lambdaOrderDetail=new LambdaQueryWrapper<>();
            lambdaOrderDetail.eq(OrderDetail::getOrderId,id);
            OrderDetail orderDetail = orderDetailMapper.selectOne(lambdaOrderDetail);
            //恢复库存
            Long itemId = orderDetail.getItemId();
            Item itemTemp = itemFeignClient.findItemById(itemId);
            Item item=new Item();
            item.setId(itemId);
            item.setSold(itemTemp.getSold()+orderDetail.getNum());
            itemFeignClient.updateItemById(item);
            //修改订单状态信息
            Order orderTemp=new Order();
            orderTemp.setId(id);
            orderTemp.setStatus(5);
            orderMapper.updateById(orderTemp);
            //删除物流信息
            LambdaQueryWrapper<OrderLogistics> lambdaOrderLogistics=new LambdaQueryWrapper<>();
            lambdaOrderLogistics.eq(OrderLogistics::getOrderId,id);
            orderLogisticsMapper.delete(lambdaOrderLogistics);
        }
    }
}
